package com.app.bussinesslocator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.app.bussinesslocator.Utils.GPSTracker;
import com.app.bussinesslocator.Utils.KeyboardHelper;
import com.app.bussinesslocator.Utils.PreferenceHelper;
import com.app.bussinesslocator.bean.ObjBussiness;
import com.app.bussinesslocator.bean.ObjOpenHours;
import com.app.bussinesslocator.httpclient.HttpClientHelper;
import com.app.bussinesslocator.httpclient.MyHttpClient;
import com.app.bussinesslocator.httpclient.MyJsonHttpResponseHandler;
import com.app.bussinesslocator.myUI.MyClickAbleImageView;

import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class MainActivity extends Activity implements  OnClickListener {

	GPSTracker gpsTracker;

	ProgressDialog progressDialog;
	double mLatitude;
	double mLongitude;
	PreferenceHelper preferenceHelper;
	
	public static ArrayList<ObjBussiness> objBussinesses = new ArrayList<ObjBussiness>();

	MyClickAbleImageView btnSearch, btnFindNear;
	Runnable r = new Runnable() {

		@Override
		public void run() {
			getLocation();
		}
	};
	
	Runnable rSearch = new Runnable() {
		
		@Override
		public void run() {
			searchFuntionBussiness();
		}
	};
	
	Runnable rPost = new Runnable() {
		
		@Override
		public void run() {
			postData();
		}
	};
	Handler mHandler = new Handler();

	// layout search
	ViewGroup llMain;
	ViewGroup llSearch, actionbar;
	ImageView imgSearch;
	EditText edtSearch;
	ImageView icClear;
	View llFocus;
	static boolean isCanloadMore = true;
	
	public static String keyword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		preferenceHelper = new PreferenceHelper(this);

		btnSearch = (MyClickAbleImageView) findViewById(R.id.btn_search);
		btnFindNear = (MyClickAbleImageView) findViewById(R.id.btn_find_near);

		actionbar = (ViewGroup) findViewById(R.id.actionbar);
		llMain = (ViewGroup) findViewById(R.id.llMain);
		llSearch = (ViewGroup) findViewById(R.id.ll_search);
		imgSearch = (ImageView) findViewById(R.id.ic_search);
		edtSearch = (EditText) findViewById(R.id.edt_search);
		icClear = (ImageView) findViewById(R.id.btn_clears);
		llFocus = (View) findViewById(R.id.llFocus);
//		KeyboardHelper.setupUI(MainActivity.this, llFocus);
//		mHandler.postDelayed(r, 2000);
		getLocation();

		init();
		/*StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

		StrictMode.setThreadPolicy(policy); */
		searchBussiness();
		
		
	}

	void init() {
		btnSearch.setOnClickListener(this);
		btnFindNear.setOnClickListener(this);

		llMain.setOnClickListener(this);
		edtSearch.setOnClickListener(this);
		llFocus.setOnClickListener(this);
		
		icClear.setOnClickListener(this);

	}
	
	
	void searchBussiness(){
		edtSearch.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH ) {
					if (edtSearch.getText().toString().matches("")){
						Toast.makeText(MainActivity.this, "Keyword is blank.", Toast.LENGTH_SHORT).show();
					} else {
						progressDialog = ProgressDialog.show(MainActivity.this, "", "Searching...");
						KeyboardHelper.hideSoftKeyboard(MainActivity.this);
						mHandler.removeCallbacks(rSearch);
						mHandler.postDelayed(rSearch, 200);
					}
					
					
					/*progressDialog = ProgressDialog.show(MainActivity.this, "", "Searching...");
					Thread thr = new Thread(new Runnable() {
						
						@Override
						public void run() {
							mHandler.removeCallbacks(rPost);
							mHandler.postDelayed(rPost, 200);
						}
					});
					thr.start();*/
					
					return true;
				}
				return false;
			}
		});

		edtSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				keyword = s.toString();
				if (keyword.length() > 0) {
					icClear.setVisibility(View.VISIBLE);
				} else {
					icClear.setVisibility(View.GONE);
				}

			}
		});
	}

	void getLocation() {
		gpsTracker = new GPSTracker(MainActivity.this);

		// check if GPS enabled
		if (gpsTracker.canGetLocation()) {

			mLatitude = gpsTracker.getLatitude();
			mLongitude = gpsTracker.getLongitude();
			
			preferenceHelper.setLAT(mLatitude);
			preferenceHelper.setLON(mLongitude);

			// \n is for new line
			// Toast.makeText(getApplicationContext(),
			// "Your Location is - \nLat: " + mLatitude + "\nLong: " +
			// mLongitude, Toast.LENGTH_LONG).show();
		} else {
			// can't get location
			// GPS or Network is not enabled
			// Ask user to enable GPS/network in settings
			gpsTracker.showSettingsAlert();
		}
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_search:
			edtSearch.setText("");
			actionbar.setVisibility(View.VISIBLE);
			llMain.setVisibility(View.GONE);
			KeyboardHelper.displaySoftKeyboard(MainActivity.this, edtSearch);
			break;
		case R.id.btn_find_near:
			gotoFindNear();
			break;
		case R.id.edt_search:
			edtSearch.requestFocus();
			imgSearch.setVisibility(View.GONE);
			break;
		case R.id.llFocus:
			KeyboardHelper.hideSoftKeyboard(MainActivity.this);
			actionbar.setVisibility(View.GONE);
			llMain.setVisibility(View.VISIBLE);
			break;
		case R.id.btn_clears:
			edtSearch.setText("");
			icClear.setVisibility(View.GONE);
			break;
		default:
			break;
		}		
	}
	
	
	void searchFuntionBussiness() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				progressDialog.dismiss();
				actionbar.setVisibility(View.GONE);
				llMain.setVisibility(View.VISIBLE);
				super.onFailure(error);
			}

			@Override
			public void onSuccess(JSONObject re) {
				super.onSuccess(re);
				try {
					int status = re.getInt("status");
					if (status == 200) {
						progressDialog.dismiss();
						JSONArray ja = re.getJSONArray("data");
						if (ja.length()<6) {
							isCanloadMore = false;
						}
						for (int i = 0; i < ja.length(); i++) {
							JSONObject data = ja.getJSONObject(i);
							Log.i("DATA", "DATA BUSSINESS: "+data.toString());
							String bussinessName = data.getString("business_name");
							String address = data.getString("address");
							float longitude = (float) data.getDouble("longitude");
							float latitude = (float) data.getDouble("latitude");
							int rating1 = data.getInt("bread");
							int rating2 = data.getInt("meat");
							int rating3 = data.getInt("filling");
							int rating4 = data.getInt("condiments");
							float overall = (float) data.getDouble("overall");
							String price = data.getString("price");
							float distance = (float) data.getDouble("distance");
							
							
							ArrayList<ObjOpenHours> objOpenHours = new ArrayList<ObjOpenHours>();
							JSONObject openHours = data.getJSONObject("open_hours");
							Iterator<String> keys = openHours.keys();
							JSONArray mt = new JSONArray();
							while (keys.hasNext()) {
								String key = keys.next();
								String value = openHours.optString(key);
								// add value to JSONArray from JSONObject
								mt.put(value);
								ObjOpenHours objOpenHour = new ObjOpenHours();
								objOpenHour.setThuNgay(key);
								objOpenHour.setThoigianMocua(value);
								objOpenHours.add(objOpenHour);
								Log.i("DATA", "" + key + " " + "" + value);
							}
							
							ObjBussiness objBussiness = new ObjBussiness();
							
							objBussiness.setBussinessName(bussinessName);
							objBussiness.setAddress(address);
							objBussiness.setLongitude(longitude);
							objBussiness.setLatitude(latitude);
							objBussiness.setRating1(rating1);
							objBussiness.setRating2(rating2);
							objBussiness.setRating3(rating3);
							objBussiness.setRating4(rating4);
							objBussiness.setOverall(overall);
							objBussiness.setDistance(distance);
							objBussiness.setPrice(price);
							objBussiness.setObjOpenHours(objOpenHours);
							
							objBussinesses.add(objBussiness);
						}
						gotoResurtSearch();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
			
		});
		
		httpClientHelper.searchByKeyWord(keyword, 0, (float) mLongitude,(float) mLatitude);
	}
	
	
	public void postData() {
	    // Create a new HttpClient and Post Header
	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost("http://www.techbusters.net.au/api/");

	    try {
	        // Add your data
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	        nameValuePairs.add(new BasicNameValuePair("keyword", keyword));
	        nameValuePairs.add(new BasicNameValuePair("page_number", "0"));
	        nameValuePairs.add(new BasicNameValuePair("latitude", String.valueOf(mLatitude)));
	        nameValuePairs.add(new BasicNameValuePair("longitude", String.valueOf(mLongitude)));
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);
	        
	        int reponseCode = response.getStatusLine().getStatusCode();
	        progressDialog.dismiss();
	        switch (reponseCode) {
			case 200:
				HttpEntity entity = response.getEntity();
				if(entity != null)
				 {
					String responseBody = EntityUtils.toString(entity);
					Log.i("DATA", "RECIVED: "+responseBody);
					try {
						JSONObject re = new JSONObject(responseBody);
						JSONArray ja = re.getJSONArray("data");
						for (int i = 0; i < ja.length(); i++) {
							JSONObject data = ja.getJSONObject(i);
							Log.i("DATA", "DATA BUSSINESS: "+data.toString());
							String bussinessName = data.getString("business_name");
							String address = data.getString("address");
							float longitude = (float) data.getDouble("longitude");
							float latitude = (float) data.getDouble("latitude");
							int rating1 = data.getInt("rating_1");
							int rating2 = data.getInt("rating_2");
							int rating3 = data.getInt("rating_3");
							int rating4 = data.getInt("rating_4");
							float overall = (float) data.getDouble("overall");
							String price = data.getString("price");
							float distance = (float) data.getDouble("distance");
							
							ObjBussiness objBussiness = new ObjBussiness();
							
							objBussiness.setBussinessName(bussinessName);
							objBussiness.setAddress(address);
							objBussiness.setLongitude(longitude);
							objBussiness.setLatitude(latitude);
							objBussiness.setRating1(rating1);
							objBussiness.setRating2(rating2);
							objBussiness.setRating3(rating3);
							objBussiness.setRating4(rating4);
							objBussiness.setOverall(overall);
							objBussiness.setDistance(distance);
							objBussiness.setPrice(price);
							
							objBussinesses.add(objBussiness);
						}
						
						gotoResurtSearch();
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				 }
				break;

			default:
				break;
			}
	        
	        
	        
	    } catch (ClientProtocolException e) {
	        // TODO Auto-generated catch block
	    } catch (IOException e) {
	        // TODO Auto-generated catch block
	    }
	}
	
	void gotoResurtSearch() {
		Intent t = new Intent(MainActivity.this, ResultSearchActivity.class);
		actionbar.setVisibility(View.GONE);
		llMain.setVisibility(View.VISIBLE);
		startActivity(t);
	}
	
	void gotoFindNear(){
		Intent t = new Intent(MainActivity.this, FindNearActivity.class);
		startActivity(t);
	}
	
}
